﻿using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using Newtonsoft.Json;
using Sustainalytics.Utils;
using System.Web.Http.Cors;
using MongoDB.Driver;
using Sustainalytics.Synchronization.Validation.ValidationRules.Common;
using Sustainalytics.ClientDW.Entities;

namespace Sustainalytics.Companies.Service.Controllers
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    [LogControllerFilter(true, true, false)]
    [RoutePrefix("api/v1/validationrulesfiles")]
    public class ValidationRulesFilesController : ApiController
    {
        private readonly IMongoCollection<WhiteList> _whiteListCollection;
        private readonly IMongoCollection<CorporateData> _corporateDataCollection;
        private ValidationRulesFilesController()
        {

        }

        public ValidationRulesFilesController(IMongoCollection<WhiteList> whiteListCollection, IMongoCollection<CorporateData> corporateDataCollection)
        {
            _whiteListCollection = whiteListCollection;
            _corporateDataCollection = corporateDataCollection;
        }
        
        [HttpPost]
        [Route("")]
        public virtual Task<HttpResponseMessage> Post()
        {
            try
            {   
                var result = Request.Content.ReadAsByteArrayAsync().ContinueWith(task =>
                {
                    if (task.IsCanceled || task.IsFaulted)
                        throw new HttpRequestException();
                    var fileData = task.Result.ToArray();
                    var validationRules = ValidationRules.GetInstance(_whiteListCollection, _corporateDataCollection);

                    var warningMessages = validationRules.ProcessFile(fileData);
                    
                    var httpStatusCode = HttpStatusCode.OK;
                    
                    return Request.CreateResponse(httpStatusCode, new { warningMessages = JsonConvert.SerializeObject(warningMessages) });
                   
                });

                return result;
            }
            catch (Exception ex)
            {   
                return (new Task<HttpResponseMessage>(() => Request.CreateResponse(HttpStatusCode.InternalServerError)));
            }
        }
    }
}
